package com.example.mongocache.service.impl;

import com.example.mongocache.pojo.News;
import com.example.mongocache.service.NewsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("newsService")
public class NewsServiceImpl implements NewsService {

    private static final Logger logger = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public News getNewsByTitle(String title) {
        Query query = new Query(Criteria.where("title").is(title));
        //从mongo数据库查询数据，这一层充当缓存
        News news = mongoTemplate.findOne(query, News.class);
        if (news == null)//缓存中没该条记录
        {
            logger.info("从数据库查询数据");
            //假设news1从数据库中查询
            News news1 = new News(title, new Date(), "", "", "bigsai");
            news1.setBrief("有了博学谷，妈妈再也不用担心我的java学习！");
            news1.setContent("博学谷优质学习资料为java学习提供更好环境,越来越多开发者学习使用");
            mongoTemplate.insert(news1, "news");
            logger.info("数据插入到MongoDB成功");
            news = news1;
        } else {
            logger.info("数据从缓存访问成功");
        }
        return news;

    }


    @Override
    public boolean updateNewsContentByTitle(String title, String content) {
        try {
            Update update = new Update();
            update.set("content", content);//更新内容
            update.set("date", new Date());//更新时间

            Query query = new Query(Criteria.where("title").is(title));
            mongoTemplate.upsert(query, update, News.class);

            //假设这里做数据库更新


        } catch (Exception e) {

            return false;
        }
        return true;

    }
}
